package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * @author Fang Lu, fanglupku@gmail.com
 */

public class FileDealer {
	public static String getFileContent(String filename) throws IOException {
		File file = new File(filename);
		FileReader fr;
		BufferedReader br;
		String oneLine;
		StringBuffer sb = new StringBuffer();

		fr = new FileReader(file);
		br = new BufferedReader(fr);
		oneLine = br.readLine();

		while (oneLine != null) {
			sb.append(oneLine);
			sb.append("\n");
			oneLine = br.readLine();
		}
		
		br.close();
		br = null;
		fr.close();
		fr = null;
		file = null;
		
		return sb.toString();
	}
	
	public static String getFileContent(String filename, String encode) throws IOException {
		File file = new File(filename);
		FileInputStream fis;
		InputStreamReader isr;
		BufferedReader br;
		String oneLine;
		StringBuffer sb = new StringBuffer();

		fis = new FileInputStream(file);
		if (encode == null){
			isr = new InputStreamReader(fis);
		}else{
			isr = new InputStreamReader(fis, encode);
		}
		br = new BufferedReader(isr);
		oneLine = br.readLine();

		while (oneLine != null) {
			sb.append(oneLine);
			sb.append("\n");
			oneLine = br.readLine();
		}
		br.close();
		br = null;
		isr.close();
		isr = null;
		fis.close();
		fis = null;
		file = null;

		return sb.toString();
	}
	
	public static int saveFile(String content, String filename) throws IOException{
		File file = new File(filename);
		FileOutputStream fos;
		OutputStreamWriter osw;
		BufferedWriter bw;
		
		fos = new FileOutputStream(file);
		osw = new OutputStreamWriter(fos);
		bw = new BufferedWriter(osw);
		bw.write(content);
		
		bw.close();
		bw = null;
		osw.close();
		osw = null;
		fos.close();
		fos = null;
		file = null;
		
		return 0;
	}
	
	public static int saveFile(String content, String filename, String encode, boolean append) throws IOException{
		File file = new File(filename);
		FileOutputStream fos;
		OutputStreamWriter osw;
		BufferedWriter bw;
		
		fos = new FileOutputStream(file, append);
		if (encode == null){
			osw = new OutputStreamWriter(fos);
		}else{
			osw = new OutputStreamWriter(fos, encode);
		}
		bw = new BufferedWriter(osw);
		bw.write(content);
		
		bw.close();
		bw = null;
		osw.close();
		osw = null;
		fos.close();
		fos = null;
		file = null;
		
		return 0;
	}
}
